﻿using Microsoft.Win32.SafeHandles;
using Microsoft.WindowsAPICodePack.Shell;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Security;
using System.Text;
using System.Windows;
using System.Windows.Interop;
using System.Windows.Media.Imaging;

namespace MonitorManager
{
    public static class ImageTool
    {
        [DllImport("gdi32.dll")] 
        private static extern bool DeleteObject(IntPtr hObject); 
        /// <summary>
        /// 从Bitmap转换成BitmapSource
        /// </summary>
        /// <param name="bmp"></param>
        /// <returns></returns>
        public static BitmapSource ChangeBitmapToBitmapSource(Bitmap bmp)
        {
            BitmapSource returnSource;
            try
            {
                IntPtr hbitmap = bmp.GetHbitmap();
                returnSource = Imaging.CreateBitmapSourceFromHBitmap(hbitmap, IntPtr.Zero, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions());
                DeleteObject(hbitmap);
                bmp.Dispose();
            }
            catch
            {
                returnSource = null;
            }
            return returnSource;
        }

        public static BitmapSource GetThumbnailByPath(string filePath)
        {
            ShellFile shellFile = ShellFile.FromFilePath(filePath);
            Bitmap shellThumb = shellFile.Thumbnail.ExtraLargeBitmap;

            return ChangeBitmapToBitmapSource(shellThumb);
        }
    }
}
